package com.crm.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.crm.po.Users;
import com.crm.task.CrmTask;
import com.crm.util.SESSION;

public class CommonFilter implements Filter {

	private static Logger logger = Logger.getLogger(CommonFilter.class);

	private String encode;

	public void destroy() {
		this.encode = null;
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fchain) throws IOException,
			ServletException {
		HttpServletRequest httpReq = (HttpServletRequest) req;
		HttpServletResponse httpResp = (HttpServletResponse) resp;

		HttpSession session = httpReq.getSession();
		String cp = httpReq.getContextPath();
		String uri = httpReq.getRequestURI();
		if (!uri.startsWith(cp + "/none")) {
			Object obj = session.getAttribute(SESSION.USER_SESSION_KEY);
			if (obj == null || !(obj instanceof Users)) {
				httpResp.sendRedirect(cp + "/none/index.jsp");
				return;
			}
		}
		if (encode != null) {
			httpReq.setCharacterEncoding(encode);
			fchain.doFilter(httpReq, resp);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// 设置字符集
		this.encode = filterConfig.getInitParameter("encode");
		// 启动数据库备份任务
		 CrmTask.readyTask();
		//CrmTask.backupMySql();

		logger.info("%%%% 过滤器初始化完成 %%%%");
	}

}
